package org.openea.eap.module.obpm.controller.custsql;

import com.alibaba.fastjson.JSONObject;
import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.rest.BaseController;
import org.openea.eap.module.obpm.service.custsql.FormCustSqlFieldsManager;
import org.openea.eap.module.obpm.service.custsql.FormCustSqlManager;
import org.openea.eap.module.obpm.service.custsql.FormCustSqlRelationManager;
import org.openea.eap.module.obpm.model.custsql.FormCustSql;
import org.openea.eap.module.obpm.model.custsql.FormCustSqlFields;
import org.openea.eap.module.obpm.model.custsql.FormCustSqlRelation;
import org.openea.eap.module.obpm.model.custsql.IdRequest;
import org.openea.eap.module.obpm.util.custsql.SqlUtil;
import org.openea.eap.module.obpm.model.custsql.vo.SqlFieldsVO;
import org.openbpm.sys.util.ContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping({"/form/formCustSql"})
public class FormCustSqlController
        extends BaseController<FormCustSql> {
    protected Logger logger = LoggerFactory.getLogger(getClass());


    @Resource
    protected FormCustSqlManager formCustSqlManager;

    @Resource
    protected FormCustSqlFieldsManager formCustSqlFieldsManager;

    @Resource
    protected FormCustSqlRelationManager formCustSqlRelationManager;


    protected String getModelDesc() {
        return "Form CustSQL List";  //自定义列表
    }


    @RequestMapping({"/parseSql"})
    @CatchErr
    public ResultMsg<List<SqlFieldsVO>> parseSql(@RequestBody FormCustSql formCustSql) throws Exception {
        return this.formCustSqlManager.parseSql(formCustSql);
    }


    @RequestMapping({"/addAliases"})
    @CatchErr
    public ResultMsg<String> addAliases(@RequestBody FormCustSql formCustSql) throws Exception {
        return SqlUtil.addAliases(formCustSql.getSqlContent());
    }


    @RequestMapping({"/save"})
    @CatchErr
    public ResultMsg<String> save(@RequestBody FormCustSql formCustSql) throws Exception {
        return this.formCustSqlManager.save(formCustSql);
    }


    @RequestMapping({"/get"})
    @CatchErr
    public ResultMsg<FormCustSql> get(@RequestParam String id) throws Exception {
        if (StringUtil.isEmpty(id)) {
            return ResultMsg.ERROR("ID不能为空");
        }

        FormCustSql formCustSql = (FormCustSql) this.formCustSqlManager.get(id);
        if (formCustSql == null) {
            return ResultMsg.ERROR("自定义列表不存在,id:" + id);
        }

        List<FormCustSqlFields> fieldsList = this.formCustSqlFieldsManager.getListBySqlId(id);
        formCustSql.setFieldsList(fieldsList);

        FormCustSqlRelation custForm = this.formCustSqlRelationManager.getByFormKey(formCustSql.getFormKey());
        formCustSql.setCustForm(custForm);

        return ResultMsg.SUCCESS(formCustSql);
    }

    @RequestMapping({"/getJson"})
    @CatchErr
    public ResultMsg<JSONObject> getJson(@RequestParam String id) throws Exception {
        if (StringUtil.isEmpty(id)) {
            return ResultMsg.ERROR("ID不能为空");
        }

        FormCustSql formCustSql = (FormCustSql) this.formCustSqlManager.get(id);
        if (formCustSql == null) {
            return ResultMsg.ERROR("自定义列表不存在,id:" + id);
        }

        List<FormCustSqlFields> fieldsList = this.formCustSqlFieldsManager.getListBySqlId(id);
        formCustSql.setFieldsList(fieldsList);

        FormCustSqlRelation custForm = this.formCustSqlRelationManager.getByFormKey(formCustSql.getFormKey());
        formCustSql.setCustForm(custForm);

        return ResultMsg.SUCCESS(formCustSqlManager.toJson(formCustSql));
    }


    @RequestMapping({"/getByCode"})
    @CatchErr
    public ResultMsg<JSONObject> getByCode(@RequestParam String code) throws Exception {
        if (StringUtil.isEmpty(code)) {
            return ResultMsg.ERROR("ID不能为空");
        }

        FormCustSql formCustSql = this.formCustSqlManager.getByCode(code, true);
        if (formCustSql == null) {
            return ResultMsg.ERROR("自定义列表不存在,code:" + code);
        }

        return ResultMsg.SUCCESS(formCustSqlManager.toJson(formCustSql));
    }


    @RequestMapping({"/remove"})
    @CatchErr
    public ResultMsg<String> remove(@RequestParam String id) throws Exception {
        String[] aryIds = StringUtil.getStringAryByStr(id);
        this.formCustSqlManager.removeCustSqlByIds(aryIds);

        return getSuccessResult(String.format("删除%s成功", new Object[]{getModelDesc()}));
    }


    @RequestMapping({"/publish"})
    @CatchErr
    public ResultMsg<String> publish(@RequestParam String id) throws Exception {
        this.logger.info("启用/发布自定义sql:{}", id);

        changeStatus(id, 1);
        return getSuccessResult("启动成功");
    }


    @RequestMapping({"/disabled"})
    @CatchErr
    public ResultMsg<String> disabled(@RequestParam String id) throws Exception {
        this.logger.info("停用/禁用自定义sql:{}", id);

        int status = 0;
        changeStatus(id, status);

        return getSuccessResult("启动成功");
    }


    @RequestMapping({"/export"})
    public void export(IdRequest request, HttpServletResponse response) throws Exception {
        this.logger.info("导出到JSON文件,IDs:{}", request.getId());
        String id = request.getId();
        if (StringUtil.isEmpty(id)) {
            return;
        }

        ResultMsg<JSONObject> exportRsp = this.formCustSqlManager.export(request.getId());

        JSONObject exportData = (JSONObject) exportRsp.getData();

        String fileName = new String(exportData.getString("fileName").getBytes("UTF-8"), "ISO8859-1");
        response.reset();

        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".json");

        PrintWriter writer = response.getWriter();
        writer.write(exportData.getString("sqls"));
        writer.flush();
        writer.close();
    }


    @RequestMapping({"/import"})
    @CatchErr
    public ResultMsg<String> importJson(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile file = request.getFile("file");

        String json = new String(file.getBytes(), "UTF-8");

        return this.formCustSqlManager.importJson(json);
    }


    private void changeStatus(String id, int status) {
        String[] aryIds = StringUtil.getStringAryByStr(id);
        for (String sqlId : aryIds) {
            FormCustSql formCustSql = (FormCustSql) this.formCustSqlManager.get(sqlId);
            if (formCustSql != null) {
                formCustSql.setStatus(Integer.valueOf(status));
                formCustSql.setUpdateTime(new Date());
                formCustSql.setUpdateBy(ContextUtil.getCurrentUserId());
                formCustSql.setUpdator(ContextUtil.getCurrentUserName());
            }
            this.formCustSqlManager.update(formCustSql);
        }
    }

    @RequestMapping({"/updateRes"})
    @CatchErr
    public ResultMsg<String> updateRes(@RequestParam String code, @RequestParam String systemId) throws Exception {

        // 获取custSql配置

        // 获取已有Res配置
        // menu: customsql_[code]  => menu id
        // button (parent=menu id): customsql_list_[code], customsql_export_[code], customsql_button_[code]_

        return getSuccessResult("启动成功");
    }
}
